//
//  EDJAppUpdate.m
//  edaijia
//
//  Created by wangfang on 14-7-10.
//
//

#import <Foundation/Foundation.h>
#import "ICAppUpdate.h"

static NSString *kSkippedVersionKey = @"kSkippedVersionKey";
static NSString *kSkippedCountKey = @"kSkippedCountKey";
static const NSInteger kAppUpdateMaxSkipCount = 5;

@interface ICAppUpdate ()

@property (nonatomic, copy) NSString *version;
@property (nonatomic, copy) NSString *latestUrl;
@property (nonatomic, copy) NSString *latestVersion;
@property (nonatomic, copy) NSString *deprecatedVersion;
@property (nonatomic, copy) NSString *updateDescription;

@end

@implementation ICAppUpdate

+ (ICAppUpdate *)shared {
    static ICAppUpdate *_shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shared = [[ICAppUpdate alloc] init];
    });
    
    return _shared;
}

- (id)init
{
    if (self = [super init]) {
        self.version = [[[NSBundle mainBundle] infoDictionary]
                        objectForKey:@"CFBundleShortVersionString"];
        self.latestUrl = @"https://itunes.apple.com/cn/app/id1074279693";
        [self getUpdateInfo];
    }
    return self;
}

- (NSString*)version
{
    return _version;
}

- (BOOL)hasDeprecated {
    /* deprecated < version <= latest */
    return ([self.version compare:self.deprecatedVersion options:NSNumericSearch] !=
            NSOrderedDescending);
}

- (BOOL)hasUpdate {
    /* deprecated < version <= latest */
    return ([self.latestVersion compare:self.version options:NSNumericSearch] ==
            NSOrderedDescending);
}

//- (BOOL)isSkipedVersion
//{
//    NSString *skipped = [[NSUserDefaults standardUserDefaults]
//                         stringForKey:kSkippedVersionKey];
//    return !([self.latestVersion compare:skipped options:NSNumericSearch] ==
//    NSOrderedDescending);
//}
//
- (void)skipLatestVersionTip
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger skippedCount = [userDefaults integerForKey:kSkippedCountKey];
    if (skippedCount < (kAppUpdateMaxSkipCount - 1)) {
        [userDefaults setInteger:++skippedCount forKey:kSkippedCountKey];
    } else {
        [userDefaults setObject:self.latestVersion
                         forKey:kSkippedVersionKey];
        [userDefaults setInteger:0 forKey:kSkippedCountKey];
    }
    [userDefaults synchronize];
}

- (void)getUpdateInfo
{
    [APP_CONTEXT.net getUpdateInfo:self.version OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        if (code == 1) {
            if ([info objectForKey:@"isNewVersion"]) {
                if ([[info objectForKey:@"isNewVersion"] isEqualToString:@"1"]) {
                    if ([info objectForKey:@"isForce"]) {
                        if ([[info objectForKey:@"isForce"] isEqualToString:@"1"]) {
//                            [self showForceUpdateAlert];
                        }else{
                            [self showUpdateAlert];
                        }
                    }

                }else{
                    
                }
            }
        }
    }];
}

//#pragma mark --version check
//- (void)appVersionCheckSuccess {
//    if (![self hasUpdate])
//        //[self activeCheck];
//        return;
//    
//    if ([self hasDeprecated]) {
//        [self showForceUpdateAlert];
//        return;
//    }
//    /* Update Alert */
//    if (![self isSkipedVersion]) {
//        [self showUpdateAlert];
//        return;
//    }
//}

- (void)gotoAppStore
{
    NSString *str = @"itms-apps://itunes.apple.com/app/id1074279693";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (void)showUpdateAlert
{
    __weak typeof(self) weakSelf = self;
    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"暂不升级" action:^{
        [weakSelf skipLatestVersionTip];
    }];
    RIButtonItem *ok = [RIButtonItem itemWithLabel:@"更新" action:^{
        [weakSelf gotoAppStore];
    }];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"新版本升级" message:nil cancelButtonItem:cancel otherButtonItems:ok,nil];
    [alertView show];
}

- (void)showForceUpdateAlert
{
    __weak typeof(self) weakSelf = self;
    RIButtonItem *ok = [RIButtonItem itemWithLabel:@"立即升级" action:^{
        [weakSelf gotoAppStore];
        exit(0);
    }];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"升级提示" message:@"研值客户端更新了，请您升级最新版本使用" cancelButtonItem:nil otherButtonItems:ok, nil];
    [alertView show];
}

@end
